package org.example.slave.packet;

import lombok.Data;

/**
 * @author dingrui
 * @since 2022/2/15
 * @description
 */

/**
 * <pre>
 *     +-------+ +------------+ +--------+
 *     | bytes | |      4     | |    1   |
 *     +-------+ +------------+ +--------+
 *     |  name | | payload_len| | seq_no |
 *     +-------+ +------------+ +--------+
 * </pre>
 */
@Data
public class HeaderPacket implements Packet {

    private int packetBodyLength;
    private byte packetSequenceNumber = 0;

    public HeaderPacket() {
    }

    public HeaderPacket(byte[] data) {
        this.fromBytes(data);
    }

    @Override
    public void fromBytes(byte[] data) {
        if (data == null || data.length != 4) {
            throw new IllegalArgumentException("invalid header data. It can't be null and the length must be 4 byte.");
        }
        this.packetBodyLength = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8) | ((data[2] & 0xFF) << 16);
        this.setPacketSequenceNumber(data[3]);
    }

    @Override
    public byte[] toBytes() {
        byte[] data = new byte[4];
        data[0] = (byte) (packetBodyLength & 0xFF);
        data[1] = (byte) (packetBodyLength >>> 8);
        data[2] = (byte) (packetBodyLength >>> 16);
        data[3] = this.getPacketSequenceNumber();
        return data;
    }
}
